<?php
include_once("adminBase.php");

class Cate extends AdminBase{
	function index()
	{
		$sql = "select * from tbl_cate where del_flg=0 order by ord desc";
		$this->db->setQuery($sql);
		$cateArr = $this->db->loadResultList('id','name');
		$dataInfo = $this->db->loadList();
		foreach($dataInfo as $key=>$value)
		{
			$sql = "select * from tbl_cate_sub where del_flg=0 and fcid='".$value['id']."' order by ord desc";
			$this->db->setQuery($sql);
			$sub = $this->db->loadList();
			if(is_array($sub) && count($sub) > 0){
				$dataInfo[$key]['sub'] = $sub;
			}
		}
		$this->smarty->assign("rows",$dataInfo);
		$this->smarty->assign("cateArr",$cateArr);
		adminDisplay("admin_cate.tpl");
	}

	function add()
	{
		$table = 'tbl_cate';
		$rowtemp['name'] = trim($_REQUEST['name']);
		$rowtemp['ord'] = intval(trim($_REQUEST['ord']));
		if(isset($_REQUEST['fcid'])){
			$rowtemp['fcid'] = trim($_REQUEST['fcid']);
			$table = 'tbl_cate_sub';
		}
		$this->db->insert($rowtemp, $table);
		$this->updateCache();
		$this->index();
	}

	function del()
	{
		$id = intval($_REQUEST['id']);
		if($_REQUEST['type'] == "sub"){
			$dbname = "tbl_cate_sub";
		}else{
			$dbname = "tbl_cate";
		}
		$sql = "update {$dbname} set del_flg=1 where id='$id'";
		$this->db->query($sql);
		$this->updateCache();
		echo ("del|".$id);die;
	}

	function save()
	{
		$id = intval($_REQUEST['id']);
		if($_REQUEST['type'] == "sub"){
			$dbname = "tbl_cate_sub";
		}else{
			$dbname = "tbl_cate";
		}
		$temprow = array();
		if($_REQUEST['name'] && $_REQUEST['name'] != ""){
			$temprow['name'] = trim($_REQUEST['name']);
		}
		if($_REQUEST['ord'] && $_REQUEST['ord'] != ""){
			$temprow['ord'] = intval(trim($_REQUEST['ord']));
		}
		$where = " where id='$id'";
		$this->db->update($temprow, $dbname, $where);
		$sql = "select id, name, ord from {$dbname} where id='{$id}'";
		$row = $this->db->loadRow($sql);
		$this->updateCache();
		echo ("save|".$id."|".$row['name']."|".$row['ord']);die;
	}

	function updateCache()
	{
		$sql = "select * from tbl_cate where del_flg=0 order by ord desc";
		$this->db->setQuery($sql);
		$cateArr = $this->db->loadResultList("id","name");
		$str = "<?php\r\n";
		$str .= $this->arrtostr($cateArr,"cateCae");
		
		$sql = "select sub.id,sub.name from tbl_cate_sub sub left join tbl_cate ca on sub.fcid=ca.id where ca.del_flg=0 and sub.del_flg=0 order by sub.ord desc";
		$this->db->setQuery($sql);
		$cateSubArr = $this->db->loadResultList("id","name");
		$str .= $this->arrtostr($cateSubArr,"cateSubCae");
		$filepath = _INC_PATH."catecae.php";
		writeFile($str, $filepath);
	}

	function arrtostr($arr,$name)
	{
		$str = "\${$name} = array(\r\n";
		foreach($arr as $key=>$value)
		{
			$str .= "\t'{$key}'=>'{$value}',\r\n";
		}
		$str .= ");\r\n";
		return $str;
	}
}

$cate = new Cate();